package com.cgs.springboottes2secrity.config;

import cn.hutool.jwt.JWT;
import com.cgs.springboottes2secrity.sec.SecAdminDetailsService;
import com.cgs.springboottes2secrity.sec.SecUserDetailsService;
import com.cgs.springboottes2secrity.secfilter.*;
import com.cgs.springboottes2secrity.vo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author cgs
 * @version woNiu 98
 * @date 2023/5/10 15:24
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig{

    //@Bean
    public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedHandler((req, resp, ex) -> {
            ex.printStackTrace();
            resp.setContentType("application/json;charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String r = objectMapper.writeValueAsString(ResponseResult.noDuty());
            resp.getWriter().write(r);
            resp.getWriter().close();
        });
        http.addFilterBefore(apiAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterAfter(jwtVerifyFilter(), ApiAuthenticationFilter.class);
        http
                .cors().configurationSource(configurationSource())
                .and().antMatcher("/api/**")
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/api/admin/login").permitAll()
                .and()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().csrf().disable();
        return http.build();
    }
    @Value("${params.secretKey}")
    private String secretKey;
    @Resource
    AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public AuthenticationManager authenticationManager(){
        try {
            return authenticationConfiguration.getAuthenticationManager();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Resource
    public void setAuthenticationManagerBuilder(AuthenticationManagerBuilder builder){
        builder.authenticationProvider(authenticationProvider())
                .authenticationProvider(jwtVerifyProvider())
                .authenticationProvider(daoAuthenticationProvider());
    }
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(secUserDetailsService());
        daoAuthenticationProvider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
        return daoAuthenticationProvider;
    }
    @Bean
    public ApiAuthenticationProvider authenticationProvider(){
        return new ApiAuthenticationProvider();
    }
    public ApiAuthenticationFilter apiAuthenticationFilter() {
        ApiAuthenticationFilter apiAuthenticationFilter = new ApiAuthenticationFilter();
        apiAuthenticationFilter.setAuthenticationManager(authenticationManager());
        //设置成功回调
        apiAuthenticationFilter.setAuthenticationSuccessHandler((req, resp, auth) -> {
            ApiAuthenticationToken apiToken = (ApiAuthenticationToken) auth;
            String token = JWT.create()
                    .setPayload("id", String.valueOf(apiToken.getId()))
                    .setPayload("account", apiToken.getPrincipal())
                    .setKey(secretKey.getBytes())
                    .sign();
            resp.setHeader("Authorization", token);
            ObjectMapper objectMapper = new ObjectMapper();
            resp.getWriter().write(objectMapper.writeValueAsString(ResponseResult.success()));
            resp.getWriter().close();
        });
        // 认证失败的回调
        apiAuthenticationFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            ObjectMapper objectMapper = new ObjectMapper();
            String r = "";
            if (ex instanceof UsernameNotFoundException) {
                r = objectMapper.writeValueAsString(ResponseResult.notFound("未找到账号信息"));

            } else if (ex instanceof BadCredentialsException) {
                r = objectMapper.writeValueAsString(ResponseResult.pwdError());
            } else {
                r = objectMapper.writeValueAsString(ResponseResult.fail());
            }
            resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            resp.getWriter().write(r);
            resp.getWriter().close();
        });
        return apiAuthenticationFilter;
    }
    private CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setExposedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", corsConfiguration);
        return source;
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .formLogin().loginPage("/user/login").loginProcessingUrl("/toLogin")
                .passwordParameter("pwd").usernameParameter("account")
                .and()
                .authorizeRequests() .antMatchers("/user/login","/toLogin").permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        http.csrf().disable();
        // ...
        return http.build();
    }
    @Bean
    public SecUserDetailsService secUserDetailsService(){
        return new SecUserDetailsService();
    }
    @Bean
    public SecAdminDetailsService secAdminDetailsService(){
        return new SecAdminDetailsService();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    public JwtVerifyFilter jwtVerifyFilter() {
        JwtVerifyFilter jwtVerifyFilter = new JwtVerifyFilter("/api/**");
        jwtVerifyFilter.setAuthenticationManager(authenticationManager());
        jwtVerifyFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            ObjectMapper objectMapper = new ObjectMapper();
            String r = objectMapper.writeValueAsString(ResponseResult.fail("JWT校验失败"));
            resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            resp.getWriter().write(r);
            resp.getWriter().close();
        });
        return jwtVerifyFilter;
    }

    @Bean
    public JwtVerifyProvider jwtVerifyProvider() {
        return new JwtVerifyProvider();
    }


    /*@Bean
    public WebSecurityCustomizer webSecurityCustomizer(WebSecurity web) {
        return (r) -> r.ignoring().antMatchers("/resources/**");
    }*/
}
